package com.hps.shiro.auth;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;

/**
 * @author heps
 * @since 2020/6/8 19:23
 */
public class Oauth2Filter implements Filter {

  private String userInfoUrl;

  public Oauth2Filter(String userInfoUrl) {
    this.userInfoUrl = userInfoUrl;
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    String accessToken = getAccessToken((HttpServletRequest) servletRequest);
    if (null == accessToken) {
      Map<String, Object> map = new HashMap<>();
      map.put("code", 401);
      map.put("msg", "未授权");
      HttpServletResponse response = (HttpServletResponse) servletResponse;
      response.setContentType("application/json;charset=utf-8");
      response.getWriter().write(JSON.toJSONString(map));
    } else {
      String userInfo = getUserInfo(accessToken);
      UserHolder.setUserInfo(userInfo);
      filterChain.doFilter(servletRequest, servletResponse);
    }
  }

  private String getAccessToken(HttpServletRequest request) {
    String accessToken = request.getHeader("accessToken");
    if (null == accessToken) {
      accessToken = request.getParameter("accessToken");
    }
    return accessToken;
  }

  private String getUserInfo(String accessToken) {
    OAuthClient oAuthClient =new OAuthClient(new URLConnectionClient());
    try {
      OAuthClientRequest userInfoRequest =new OAuthBearerClientRequest(userInfoUrl)
          .setAccessToken(accessToken).buildQueryMessage();

      OAuthResourceResponse resourceResponse =oAuthClient.resource(userInfoRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
      String body = resourceResponse.getBody();
      System.out.println("==> 客户端通过accessToken："+ accessToken +"  从服务端获取用户信息为："+body);
      return body;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
